require('app-module-path').addPath(__dirname + '/')

const app = new(require('koa'))()
const cors = require('kcors')

const conf = require('./config')

// 静态页面
const views = require('koa-views')

const convert = require('koa-convert')
const bodyparser = require('koa-bodyparser')()
const json = require('koa-json')
const logger = require('koa-logger')

const session = require('koa-session2')
const helmet = require('koa-helmet')

const mongodb = require('db/mongodb')
const redis = require('db/redis')
const router = require('./routes')
const middlewares = require('./middlewares')
const utils = require('./utils')

mongodb.connect()
// utils.github()
// utils.email.verifyClient()

const start = async app => {
	// app.use(cookie())
	app.use(cors({
		credentials: true
	}))

	app.use(convert(logger()))

	app.use(convert(require('koa-static')(__dirname + '/public')))
	app.use(convert(bodyparser))
	app.use(convert(json()))

	app.use(session({
		key: conf.redisKey,
		store: redis,
		httpOnly: true
	}, app))

	app.use(helmet())

	app.use(async(ctx, next) => {
		ctx.state = {
			username: ctx.session.username || false
		}
		await next()
	})

	app.use(views(__dirname + '/views', {
		map: {
			html: 'nunjucks'
		}
	}))

	app.use(async(ctx, next) => {
		const start = new Date()
		await next()
		const ms = new Date() - start
		console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
	})

	app.use(middlewares.errorHandler)

	app.use(router.routes(), router.allowedMethods())

	app.listen(conf.port, () => {
		console.log(`server begin on : ${conf.port}`)
	})
}
start(app)